﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.RoleCommand;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.RoleHandler
{
    public class GetRoleHandler : IRequestHandler<GetRoleCommand, APIPaging<Role>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly ILogger<GetRoleHandler> logger;

        public GetRoleHandler(IBaseRepository<Role> roleRep, ILogger<GetRoleHandler> logger)
        {
            this.roleRep = roleRep;
            this.logger = logger;
        }

        public Task<APIPaging<Role>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            APIPaging<Role> result = new APIPaging<Role>();
            try
            {
                result.Code = APIEnum.Mvc;
                result.Msg = "查询成功";
                var model = roleRep.GetAll().Where(x => x.IsDeleted == false).ToList();
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    model = model.Where(x=>x.RoleName==request.RoleName).ToList();
                }
                result.TotalCount = model.Count;
                result.PageCount = (int)Math.Ceiling(result.TotalCount*1.0 / request.PageSize);
                result.Data = model.OrderBy(x=>x.RoleId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
